package com.example.android.story.ui;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.android.story.R;
import com.example.android.story.Utils.Story;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by liwei on 2018/5/27.
 */

public class StoryAdapter extends RecyclerView.Adapter<StoryAdapter.ViewHolder> {

    private List<Story> mStories=new ArrayList<>();
    private OnItemClickListener onItemClickListener;

    public StoryAdapter(OnItemClickListener onItemClickListener){
        this.onItemClickListener=onItemClickListener;
    }
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext())
                .inflate(R.layout.story_item,parent,false);
        ViewHolder holder=new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        final Story story=mStories.get(position);
        holder.mTextView.setText(story.getTitle());
//        holder.mImageView.setImageResource(R.drawable.no4);
        holder.mImageView.setImageBitmap(getThumbnail(story.getPicture()));
        holder.mImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(onItemClickListener!=null)
                    onItemClickListener.onClick(story);
            }
        });
    }

    private Bitmap getThumbnail(String filepath) {
        final int THUMBSIZE = 500;
        Bitmap origin=BitmapFactory.decodeFile(filepath);
        if(origin==null)
            return null;
        double ratio=(double)500/origin.getWidth();
        Bitmap thumbImage = ThumbnailUtils.extractThumbnail(origin,
                THUMBSIZE, (int)(ratio*THUMBSIZE));
        return thumbImage;
    }

    @Override
    public int getItemCount() {
        return mStories.size();
    }


    public void setStories(List<Story> mStories) {
        this.mStories = mStories;
    }

    static class ViewHolder extends RecyclerView.ViewHolder{
        private ImageView mImageView;
        private TextView mTextView;
        public ViewHolder(View itemView) {
            super(itemView);
            this.mImageView=(ImageView) itemView.findViewById(R.id.story_picture);
            this.mTextView=(TextView)itemView.findViewById(R.id.story_name);
        }
    }

    public interface OnItemClickListener{
        public void onClick(Story story);
    }
}
